using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Tools.Domain.Specifications;
using System.Web;
using Web.App.Infrastructure.Extensions;
using Web.App.Infrastructure.ObjectStore.Contracts;

namespace Web.App.Infrastructure.ObjectStore.Implementation
{
    public class SessionBasedObjectStore : IObjectStoreRepository
    {

        private IList<ObjectStoreItem> Items
        {
            get
            {
                var items = HttpContext.Current.Session["ObjectStoreItems"] as IList<ObjectStoreItem>;
                if(!items.Exists())
                {
                    items = new List<ObjectStoreItem>();
                    HttpContext.Current.Session["ObjectStoreItems"] = items;
                }
                return items;
            }
        }


        public void Add(ObjectStoreItem item)
        {
            Items.Add(item);
        }

        public ObjectStoreItem Add(object data, string description)
        {
            var newItem = new ObjectStoreItem(Guid.NewGuid(), data, DateTime.Now, data.GetType(), description);
            Add(newItem);
            return newItem;
        }

        public void Update(Guid id, object data)
        {
            var item = Items.Where(x => x.Id == id).First();
            item.Data = data;
        }

        public void Remove(ObjectStoreItem item)
        {
            Items.Remove(item);
        }

        public void Remove(Guid id)
        {
            throw new System.NotImplementedException();
        }

        public IEnumerable<ObjectStoreItem> Find(Func<ObjectStoreItem, bool> predicate)
        {
            return Items.Where(predicate);
        }

        public IEnumerable<ObjectStoreItem> Find(ISpecification<ObjectStoreItem> predicate)
        {
            throw new NotImplementedException();
        }

        public ObjectStoreItem Find(Guid id)
        {
            return Items.Where(item => item.Id == id).FirstOrDefault();
        }
    }
}